package com.czy.owner.ui.packagecardproject;

import android.content.Intent;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.czy.owner.R;
import com.czy.owner.adapter.MyPackageCardProjectAdapter2;
import com.czy.owner.api.OwnerPacMyApi;
import com.czy.owner.db.UserHelper;
import com.czy.owner.entity.MyPackageEntity;
import com.czy.owner.global.Constants;
import com.czy.owner.net.api.BaseResultEntity;
import com.czy.owner.net.http.HttpManager;
import com.czy.owner.net.listener.HttpOnNextListener;
import com.czy.owner.rxbus.RxBus;
import com.czy.owner.rxbus.Subscribe;
import com.czy.owner.rxbus.ThreadMode;
import com.czy.owner.rxbus.event.CommonEvent;
import com.czy.owner.ui.BaseActivity;
import com.czy.owner.ui.setting.SettingActivity;
import com.czy.owner.utils.MyLog;
import com.czy.owner.utils.PhoneUtils;
import com.czy.owner.widget.UniversalDialog;
import com.easyrecycleview.EasyRecyclerView;
import com.easyrecycleview.adapter.RecyclerArrayAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;

/**
 * Created by wangyang on 2017/5/12 0012.
 * 套餐卡项
 */

public class MyPackageCardProjectActivity extends BaseActivity implements RecyclerArrayAdapter.OnLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, MyPackageCardProjectAdapter2.IonSlidingViewClickListener {
    @BindView(R.id.easy_recycleview)
    EasyRecyclerView easyRecyclerView;
    private MyPackageCardProjectAdapter2 adapter = null;
    private Handler handler = new Handler();
    private int page = 1;

    @Override
    protected int attachLayoutRes() {
        return R.layout.common_activity_easyrecycleview;
    }

    @Override
    protected void initInjector() {

    }

    @Override
    protected void initViews() {
        getToolbarTitle().setText(getString(R.string.my_package_card));
//        getSubTitle().setText(getString(R.string.my_package_card_buy));
        RxBus.getDefault().register(this);
        initRecycleView();
    }

    @Override
    protected void updateViews() {

    }

//    @OnClick(R.id.toolbar_subtitle)
//    public void bugPackageCard(View view) {
//        Intent intent = new Intent(MyPackageCardProjectActivity.this, PackageCardProjectActivity.class);
//        startActivity(intent);
//    }

    private void initRecycleView() {
        easyRecyclerView.setLayoutManager(new LinearLayoutManager(MyPackageCardProjectActivity.this));
        easyRecyclerView.setAdapterWithProgress(adapter = new MyPackageCardProjectAdapter2(MyPackageCardProjectActivity.this));
        adapter.setMore(R.layout.view_more, this);
        adapter.setNoMore(R.layout.view_nomore, new RecyclerArrayAdapter.OnNoMoreListener() {
            @Override
            public void onNoMoreShow() {
                //adapter.resumeMore();
            }

            @Override
            public void onNoMoreClick() {
                adapter.resumeMore();
            }
        });

        adapter.setError(R.layout.view_error_net, new RecyclerArrayAdapter.OnErrorListener() {
            @Override
            public void onErrorShow() {
                adapter.resumeMore();

            }

            @Override
            public void onErrorClick() {
                adapter.resumeMore();

            }
        });
        easyRecyclerView.setRefreshListener(this);
        onRefresh();


//        adapter.setOnItemClickListener(new RecyclerArrayAdapter.OnItemClickListener<MyPackageEntity>() {
//            @Override
//            public void onItemClick(View view,int position, MyPackageEntity model) {
//                if (PhoneUtils.isNetworkConnected(MyPackageCardProjectActivity.this)) {
//                    Intent ti = new Intent(MyPackageCardProjectActivity.this, MyPackageCardDetailActivity.class);
//                    ti.putExtra("userPackageId", model.getUserPackageId());
//                    startActivity(ti);
//                }
//            }
//        });
    }

    private void getDataList() {
        OwnerPacMyApi ownerPacMyApi = new OwnerPacMyApi(new HttpOnNextListener<List<MyPackageEntity>>() {
            @Override
            public void onNext(List<MyPackageEntity> list) {
                MyLog.e("yang", "************************************");
                setDataList(list);
            }


            @Override
            public void onCacheNext(String cache) {
                super.onCacheNext(cache);
                Gson gson = new Gson();
                Type type = new TypeToken<BaseResultEntity<List<MyPackageEntity>>>() {
                }.getType();
                BaseResultEntity<List<MyPackageEntity>> cacheList = gson.fromJson(cache, type);
                setDataList(cacheList.getData());


            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                PhoneUtils.ShowToastMessage(MyPackageCardProjectActivity.this, e.getMessage());
            }
        }, this, page + "");
        ownerPacMyApi.setSession(UserHelper.getInstance().getSessionInfoModel(this).getSession());
        ownerPacMyApi.setStoreId(0 + "");
        ownerPacMyApi.setPackageName("");
        ownerPacMyApi.setPage(page + "");
        ownerPacMyApi.setSize("10");
        HttpManager manager = HttpManager.getInstance();
        manager.doHttpDeal(ownerPacMyApi);

    }


    private void setDataList(List<MyPackageEntity> list) {
        if (list.size() < 9) {
            adapter.stopMore();
        }
        adapter.addAll(list);
        if (adapter.getAllData().size() == 0) {
            easyRecyclerView.setEmptyView(R.layout.view_empty_common);
            easyRecyclerView.showEmpty();
        }
    }

    @Override
    public void onRefresh() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //刷新
                adapter.clear();
                page = 1;
                getDataList();
            }
        }, 1000);
    }

    @Override
    public void onLoadMore() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                //加载更多
                if (!PhoneUtils.isNetworkConnected(MyPackageCardProjectActivity.this)) {
                    adapter.pauseMore();
                    easyRecyclerView.showError();
                    return;
                }
                page++;
                getDataList();

            }
        }, 1000);
    }

    @Subscribe(code = Constants.BUY_PACKAGE_SUCCESS_CODE, threadMode = ThreadMode.MAIN)
    public void eventCode(CommonEvent bugPackageEvent) {
        onRefresh();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxBus.getDefault().unRegister(this);
    }

    @Override
    public void onItemClick(View view, int position, MyPackageEntity model) {
        if (PhoneUtils.isNetworkConnected(MyPackageCardProjectActivity.this)) {
            Intent ti = new Intent(MyPackageCardProjectActivity.this, MyPackageCardDetailActivity.class);
            ti.putExtra("userPackageId", model.getUserPackageId());
            startActivity(ti);
        }
    }

    @Override
    public void onDeleteBtnCilck(View view, final int position, final MyPackageEntity model) {
        new UniversalDialog(MyPackageCardProjectActivity.this).builder().setTitle("提示")
                .setMsg("是否删除已过期套餐")
                .setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!model.getStatus().equals("normal")) {
                            mLoadView.ShowLoadView();
                            String url = Constants.APP_API_BASE + Constants.OWN_PAC_DELUSERPACKAGE;
                            RequestParams params = new RequestParams(url);
                            params.addBodyParameter("session", UserHelper.getInstance().getSession(MyPackageCardProjectActivity.this));
                            params.addBodyParameter("userPackageId", model.getUserPackageId() + "");
                            x.http().post(params, new Callback.CommonCallback<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    MyLog.e("yang", "onSuccess==" + result);
                                    String data = PhoneUtils.checkResponseFlag(MyPackageCardProjectActivity.this, result);
                                    if (data != null) {
                                        adapter.removeData(position);
                                    }

                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    MyLog.e("yang", "onError==" + ex.toString());
                                }

                                @Override
                                public void onCancelled(CancelledException cex) {

                                }

                                @Override
                                public void onFinished() {
                                    mLoadView.CancleLoadView();
                                }
                            });
                        } else {
                            PhoneUtils.ShowToastMessage(MyPackageCardProjectActivity.this, "该套餐未过期,不能删除");
                        }

                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).show();


    }


}
